package com.sduept.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;

public class WebRequestUtil {
	/**
	 * <Hearders>
		<LoginURL value="http://10.50.13.135:8080/fis/j_spring_security_check"></LoginURL>
		<LoginParams name="username" value="111"/>
		<LoginParams name="password" value="111" md5="true" />
		<RequestURL value="http://10.50.13.135:8080/fis/rest/query/ied"></RequestURL>
		<RequestMethod value="POST"></RequestMethod>
		<RequestContentType value="application/x-www-form-urlencoded; charset=UTF-8"></RequestContentType>
		<RequestParams name="pname" value="pname"/>
		<RequestParams name="pname" value="pname"/>
		<RequestParams name="pname" value="pname"/>
		<RequestParams name="pname" value="pname"/>
		<ResponseCharset value="UTF-8"></ResponseCharset>
		<ResponseDatasPageSizeKey value="pageSize"></ResponseDatasTotalKey>
		<ResponseDatasPageIndexKey value="pageIndex"></ResponseDatasTotalKey>
		<ResponseDatasTotalKey value="total"></ResponseDatasTotalKey>
		<ResponseDatasKey value="data"></ResponseDatasKey>
		</Hearders>
	 */
	public final static String CONTENT_TYPE = "Content-Type";
    public final static String userAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";
    private WebRequestUtil(){}
    /**
     * @param loginUrl
     * @param loginParams
     * @param requestUrl
     * @param requestParams
     * @return
     * @throws Exception
     */
    public static String getRequestWithLogin(String loginUrl,Map<String,String> loginParams,String requestUrl,Map<String,String> requestParams) throws Exception{
    	Connection loginConn = Jsoup.connect(loginUrl)
    			.ignoreContentType(true)
    			.userAgent(userAgent);
    	for(Map.Entry<String, String> et : loginParams.entrySet()){
    		loginConn.data(et.getKey(),et.getValue());
    	}
    	loginConn.method(Method.POST);
    	Connection.Response  loginRes = loginConn.execute();
    	Connection requestConn =  Jsoup.connect(requestUrl).ignoreContentType(true)
            	.cookies(loginRes.cookies())
			.ignoreContentType(true)
			.userAgent(userAgent)
			.method(Method.POST);
    	for(Map.Entry<String, String> et : requestParams.entrySet()){
    		requestConn.data(et.getKey(),et.getValue());
    	}
    	Connection.Response  requestRes = requestConn.execute();
    	return requestRes.body();
    }
    
	 /**
	  * 鑾峰彇缃戦〉鍐呭锛屽彲涓簀son瀵硅薄锛屼篃鍙兘鏄痟tml椤甸潰
	 * @param url
	 * @param method
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String getRequest(String url,Method method,Map<String,String> requestParams) throws Exception{
	    	Connection con = Jsoup.connect(url)
	    			.timeout(1000*10)
	    			.userAgent(userAgent).ignoreContentType(true)
	    			.method(method);
	    	for(Map.Entry<String, String> et : requestParams.entrySet()){
	    		con.data(et.getKey(),et.getValue());
	    	}
	    	Connection.Response  res = con.execute();
	    	return res.body();
	    }
	    /**
	     * 鑾峰彇涓嬭浇鏂囦欢锛屼粎閫傜敤浜庣洿鎺ヤ笅杞芥枃浠�
	     * @param url
	     * @param method
	     * @param allPath
	     * @param cookies
	     * @param params
	     * @throws Exception
	     */
	    public static void getDownLoadFile(String url,Method method,String allPath,Map<String, String> cookies,String...params) throws Exception{
	    	Connection.Response  res = 
	    			Jsoup.connect(url).ignoreContentType(true)
	    			.userAgent(userAgent)
	    			.cookies(cookies)
	    			.data(params)
	    			.method(method)
	    			.execute();
			FileOutputStream fos = new FileOutputStream(allPath);
			fos.write(res.bodyAsBytes());
			fos.close();
			
	    }
	    /**
	     * 杩斿洖cookie
	     * @param url
	     * @param params
	     * @return
	     * @throws Exception
	     */
	    public static  Map <String,String>  login(String url,String... params) throws Exception{
	    	Connection con = Jsoup.connect(url)
	    			.ignoreContentType(true)
	    			.userAgent(userAgent);
	    		con.data(params);
	    	 Connection.Response  res = con.method(Method.POST)
	                     .execute();
			return res.cookies();
	    }

		/**
		 * 閫氳繃soap鍗忚璋冪敤webService锛屽苟鎷垮埌杩斿洖鍊�
		 * 
		 * @param postUrl
		 * @param soapXml
		 * @return
		 */
		public static String invokeWebServiceBySoap(String postUrl, String soapXml, String soapAction) throws IOException {
			StringBuffer result = new StringBuffer();
			HttpPost httpPost = new HttpPost(postUrl);
			StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10 * 1000).setConnectionRequestTimeout(5 * 1000).setConnectTimeout(10 * 1000).build();
			httpPost.setConfig(requestConfig);
			httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
			// 鏍规嵁瀹為檯鍒ゆ柇鏄惁闇�瑕丼oapAction
			if (StringUtils.isNotEmpty(soapAction)) {
				httpPost.setHeader("SOAPAction", soapAction);
			}
			httpPost.setEntity(data);
			try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = closeableHttpClient.execute(httpPost);) {
				HttpEntity httpEntity = response.getEntity();
				if (httpEntity != null) {
					result.append(EntityUtils.toString(httpEntity, "UTF-8"));
				}
			}
			return result.toString();
		}

}
